package com.app.utils;


import java.io.File;
import java.lang.ref.WeakReference;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

/**
 * 裁剪照片,要在onActivityResult中调用该实例的onActivityResult方法<br>
 * 在ClipPhotoListener接口监听裁剪完成返回图片地址
 * 
 */
public class ClipPhoto {

	private ClipPhotoListener  listener;
	private static final int SELECT_PIC_KITKAT = 5000;
	private static final int SELECT_PIC = 5001;

	private static final int REQUESTCODE_CAMERA = 1000;
	private static final int final_requestCode = 1001;

	private  String IMAGE_FILE_LOCATION;
	private  Uri imageUri;
	/**
	 * 图片长宽
	 */
	private  static  int DEFAULT_OUT_PUT_XY = 100;
	
	private int aspectX = 1;
	private int aspectY = 1;
	private int outputX = DEFAULT_OUT_PUT_XY;
	private int outputY = DEFAULT_OUT_PUT_XY;
	
	
	
	private boolean isClip = true;
	private WeakReference<Activity> mActivityRef;

	public ClipPhoto(Activity activity) {
		mActivityRef = new WeakReference<Activity>(activity);
		IMAGE_FILE_LOCATION = "file://"+ Environment.getExternalStorageDirectory() + "/default.png";
		imageUri = Uri.parse(IMAGE_FILE_LOCATION);
	}
	public ClipPhoto(Activity activity,String fileName,int aspectX ,int aspectY,int outputX,int outputY) {
		mActivityRef = new WeakReference<Activity>(activity);
		IMAGE_FILE_LOCATION = "file://"+ Environment.getExternalStorageDirectory() + "/"+fileName+".png";
		imageUri = Uri.parse(IMAGE_FILE_LOCATION);
		this.aspectX = aspectX;
		this.aspectY = aspectY;
		this.outputX = outputX;
		this.outputY = outputY;
	}
	
	
	public ClipPhoto(Activity activity,String fileName) {
		mActivityRef = new WeakReference<Activity>(activity);
		IMAGE_FILE_LOCATION = "file://"+ Environment.getExternalStorageDirectory() + "/"+fileName+".png";
		imageUri = Uri.parse(IMAGE_FILE_LOCATION);
	}

	private ClipPhoto(Activity activity,boolean isClip) {
		mActivityRef = new WeakReference<Activity>(activity);
		this.isClip = isClip;
		
	}
	
	public ClipPhoto(Activity activity,int outputXY) {
		mActivityRef = new WeakReference<Activity>(activity);
		this.isClip = true;
		this.outputX = outputXY;
		this.outputY = outputXY;
	}
	
	
	/**
	 * 拍照
	 */
	public void getFromCamera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		Activity activity = mActivityRef.get();
		if(activity == null)return;
		activity.startActivityForResult(intent, REQUESTCODE_CAMERA);
	}

	/**
	 * 相册
	 */
	public void getPhotoFromLibrary() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		Activity activity = mActivityRef.get();
		if(activity == null)return;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			activity.startActivityForResult(intent, SELECT_PIC_KITKAT);
		} else {
			activity.startActivityForResult(intent, SELECT_PIC);
		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUESTCODE_CAMERA:
			if (resultCode == Activity.RESULT_OK){
				if(isClip)
				cropImageUri(imageUri, outputX, outputY, final_requestCode);
				else 
					if(listener!=null)listener.ClipPhotoDone(imageUri.getPath());
			}

			break;

		case SELECT_PIC_KITKAT:
		case SELECT_PIC:
			if (resultCode == Activity.RESULT_CANCELED)return;
			if(isClip)
			startPhotoZoom(data.getData());
			else {
				Activity activity = mActivityRef.get();
				if(activity == null)return;
				String url = getPath(activity, data.getData());
				if(listener!=null)listener.ClipPhotoDone(url);
			}
			
			break;
		case final_requestCode:
			if (resultCode == Activity.RESULT_CANCELED)return;
			if(listener!=null)listener.ClipPhotoDone(imageUri.getPath());
			break;
		}
	}

	/**
	 * 裁剪图片
	 * 
	 * @param uri
	 * @param outputX
	 * @param outputY
	 * @param requestCode
	 */
	private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", aspectX);
		intent.putExtra("aspectY",aspectY);
		intent.putExtra("outputX", outputX);
		intent.putExtra("outputY", outputY);
		intent.putExtra("scale", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		intent.putExtra("return-data", false);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
		intent.putExtra("noFaceDetection", true);
		Activity activity = mActivityRef.get();
		if(activity == null)return;
		activity.startActivityForResult(intent, requestCode);
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	private  void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			Activity activity = mActivityRef.get();
			if(activity == null)return;
			String url = getPath(activity, uri);
			intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");
		} else {
			intent.setDataAndType(uri, "image/*");
		}
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", aspectX);
		intent.putExtra("aspectY", aspectY);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", outputX);
		intent.putExtra("outputY", outputY);
		intent.putExtra("return-data", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
		Activity activity = mActivityRef.get();
		if(activity == null)return;
		activity.startActivityForResult(intent, final_requestCode);
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	private static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	private static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	private static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	private static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri
				.getAuthority());
	}

	// 以下是关键，原本uri返回的是file:///...来着的，android4.4返回的是content:///...
	@SuppressLint("NewApi")
	private  String getPath(final Context context, final Uri uri) {

		final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
		// DocumentProvider
		if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
			// ExternalStorageProvider
			if (isExternalStorageDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/"
							+ split[1];
				}

			}
			// DownloadsProvider
			else if (isDownloadsDocument(uri)) {
				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(
						Uri.parse("content://downloads/public_downloads"),
						Long.valueOf(id));

				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if (isMediaDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				final String selection = "_id=?";
				final String[] selectionArgs = new String[] { split[1] };

				return getDataColumn(context, contentUri, selection,
						selectionArgs);
			}
		}
		// MediaStore (and general)
		else if ("content".equalsIgnoreCase(uri.getScheme())) {
			// Return the remote address
			if (isGooglePhotosUri(uri))
				return uri.getLastPathSegment();

			return getDataColumn(context, uri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}

	/**
	 * Get the value of the data column for this Uri. This is useful for
	 * MediaStore Uris, and other file-based ContentProviders.
	 * 
	 * @param context
	 *            The context.
	 * @param uri
	 *            The Uri to query.
	 * @param selection
	 *            (Optional) Filter used in the query.
	 * @param selectionArgs
	 *            (Optional) Selection arguments used in the query.
	 * @return The value of the _data column, which is typically a file path.
	 */
	private static String getDataColumn(Context context, Uri uri,
			String selection, String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = { column };

		try {
			cursor = context.getContentResolver().query(uri, projection,
					selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				final int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}
	
	
	
	public  void setClipPhotoDoneListener(ClipPhotoListener listener ){
		this.listener = listener;
	}
	
	/**
	 * 裁剪完成接口
	 *
	 */
	public interface ClipPhotoListener{
		
		/**
		 * 做 裁剪完成后的事
		 * @param url 裁剪后的图片地址
		 */
		void ClipPhotoDone(String url);
	}
}
